package com.example.neusoft.sqlitedemo;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import java.util.List;

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{
    Button button_add, button_deleteall;
    RecyclerView recyclerView;
    Context context;
    List<ContactBean> list;
    MyRVAdapter rvAdapter;
    RecyclerView.LayoutManager layoutManager;
    ContactDBAdapter dbAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        context=MainActivity.this;

        //获取ContactDBAdapter的实例？？
        dbAdapter=ContactDBAdapter.getInstance(context);
        //打开数据库？？
        dbAdapter.openDB();
        //读取数据库的数据，形成list？？
        list=dbAdapter.queryAll();

        rvAdapter=new MyRVAdapter(context,list);
        layoutManager=new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(rvAdapter);
    }

    void initView() {
        button_add = (Button) findViewById(R.id.button_contact_add);
        button_deleteall = (Button) findViewById(R.id.button_contact_deleteall);
        button_add.setOnClickListener(this);
        button_deleteall.setOnClickListener(this);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.button_contact_add:
                Intent intent1=new Intent(context, AddContactActivity.class);
                startActivity(intent1);
                break;

            case R.id.button_contact_deleteall:
                //从数据库中删除所有数据
                dbAdapter.deleteAll();
                //清空list
                rvAdapter.clearList();
                //通知listview数据刷新
                rvAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void onResume() {//由AddContactActivity返回时执行
        // TODO Auto-generated method stub
        super.onResume();
        //读取数据库的数据，重新生成list
        list=dbAdapter.queryAll();
        //更新adapter中的list对象
        rvAdapter.setList(list);
        //通知listview数据刷新
        rvAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {//当应用退出时执行关闭数据库的操作
        // TODO Auto-generated method stub
        super.onDestroy();
        dbAdapter.closeDB();
    }
}
